package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.nursing.domain.NursingElder;
import com.zzyl.nursing.dto.AlertDataDto;
import com.zzyl.nursing.dto.AlertDataPageDto;
import com.zzyl.nursing.dto.ProcessDto;
import com.zzyl.nursing.service.INursingElderService;
import com.zzyl.nursing.vo.AlertDataPageVo;
import com.zzyl.nursing.vo.AlertPageResult;
import com.zzyl.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.service.IAlertDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 报警数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-05
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return getById(id);
    }

    @Autowired
    private INursingElderService nursingElderService;
    @Autowired
    private IAlertDataService alertDataService;

    /**
     * 查询报警数据列表
     *
     * @param alertDataDto 查询条件
     */
    @Override
    public List<AlertData> selectAlertDataList(AlertDataDto alertDataDto) {
        Long userId = SecurityUtils.getUserId();
        if (SecurityUtils.isAdmin(userId)) {
            return alertDataMapper.selectAlertDataList(alertDataDto);
        } else {
            List<NursingElder> nursingElderList = nursingElderService.lambdaQuery()
                                                                     .eq(NursingElder::getNursingId, userId)
                                                                     .list();
            if (CollUtil.isEmpty(nursingElderList)) {
                throw new BaseException("该员工不负责老人");
            }
            List<AlertData> alertDataList = new ArrayList<>();
            nursingElderList.forEach(nursingElder -> {
                Long elderId = nursingElder.getElderId();
                List<AlertData> list = alertDataService.lambdaQuery().eq(AlertData::getAccessLocation, elderId)
                                                       .list();
                CollUtil.addAll(alertDataList, list);
            });

            CollUtil.distinct(alertDataList);

            return alertDataList;
        }
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAlertDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 处理报警数据
     *
     * @param processDto 处理报警数据
     */
    @Override
    public void handleAlertData(ProcessDto processDto) {

        AlertData alertData = alertDataMapper.selectAlertDataById(processDto.getId());
        LocalDateTime processingTime = processDto.getProcessingTime();
        alertData.setProcessingTime(processingTime);
        alertData.setProcessingResult(processDto.getProcessingResult());
        alertData.setStatus(1);
        //处理人id
        Long userId = SecurityUtils.getUserId();
        alertData.setProcessorId(userId);

        //查询处理人的名字
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        String userName = sysUser.getUserName();
        alertData.setProcessorName(userName);

        updateById(alertData);
    }

    /**
     * 分页查询报警数据
     *
     * @param alertDataPageDto 查询条件
     * @return 分页数据
     */
    @Override
    public AlertPageResult pageQueryAlertData(AlertDataPageDto alertDataPageDto) {
        // 2.查询分页数据
        // 2.1 将时间戳改为时间
        LocalDateTime startTime = LocalDateTimeUtil.of(new Date(alertDataPageDto.getStartTime()));
        LocalDateTime endTime = LocalDateTimeUtil.of(new Date(alertDataPageDto.getEndTime()));
        // 2.2 查询分页数据
        List<AlertDataPageVo> alertDataPageVos = alertDataMapper.pageQueryAlertData(
                alertDataPageDto.getIotId(), alertDataPageDto.getFunctionId(), startTime, endTime);

        // 3. 将 List 包装成 Page 对象
        return new AlertPageResult(alertDataPageVos.size(), alertDataPageVos);
    }
}
